package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gap.basic.exception.BizException;
import com.gap.cache.redis.RedisCache;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.redis.LatestLog;
import com.mingqijia.gassafety.db.entity.vo.*;
import com.mingqijia.gassafety.db.mapper.*;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.dto.UserFuncCodePermissionDTO;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.DateFormatUtil;
import com.mingqijia.gassafety.shared.utils.HttpUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.webserver.request.CustDetailRequest;
import com.mingqijia.gassafety.webserver.request.ScreenSmallBellListRequest;
import com.mingqijia.gassafety.webserver.response.*;
import com.mingqijia.gassafety.webserver.response.sk.AlarmSupplierListVo;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkAlarmSecurityDeviceDataResponse;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkSecurityDeviceDatalist;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkSupplierListResponse;
import com.mingqijia.gassafety.webserver.service.*;
import com.mingqijia.gassafety.webserver.service.cmp.EquipmentCmpService;
import com.mingqijia.gassafety.webserver.service.workorder.WorkOrderHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.IS_DELETED_FALSE;
import static com.mingqijia.gassafety.shared.constant.Constants.ORG_MAP_SUBSCODE;
import static com.mingqijia.gassafety.webserver.constant.DeviceConstant.*;
import static com.mingqijia.gassafety.shared.constant.Constants.*;
import static com.mingqijia.gassafety.webserver.constant.DeviceConstant.VALVE_WORK_STATUS_BROKEN;

/**
 * @program: gassafety
 * @description:
 * @author: Mr.Wang
 * @create: 2022-12-12 11:28
 **/

@Service
@Slf4j
public class CockpitServiceImpl implements CockpitService {

    @Value(value = "${asst.workOrder.doamin.url}")
    String workOrderUrl;
    @Autowired
    RedisCache redisCache;
    @Autowired
    private WorkOrderHistoryMapper workOrderHistoryMapper;

    @Autowired
    private ReceiverValveService receiverValveService;

    @Autowired
    FieldTemplateService fieldTemplateService;
    @Autowired
    private ConsumerMapper consumerMapper;

    @Autowired
    private HistoryAlarmMapper historyAlarmMapper;
    @Autowired
    private HistoryBrokenMapper historyBrokenMapper;
    @Autowired
    ConsumerService consumerService;

    @Autowired
    DtuMapper dtuMapper;

    @Autowired
    LatestLogService latestLogService;

    @Autowired
    ConfigureHolder holder;

    @Autowired
    EquipmentService equipmentService;

    @Autowired
    DtuBindingOrderMapper dtuBindingOrderMapper;
    @Autowired
    DeviceStateMapper deviceStateMapper;
    @Autowired
    HttpUtil httpUtil;

    @Autowired
    OrganizationService organizationService;

    @Autowired
    HistoryAlarmService historyAlarmService;

    @Autowired
    HistoryBrokenService historyBrokenService;

    @Autowired
    AppealLogMapper appealLogMapper;

    @Autowired
    CompanyService companyService;

    @Autowired
    private ConsoleSkFeignClient consoleSkFeignClient;

    @Autowired
    EquipmentCmpService equipmentCmpService;

    @Autowired
    WorkOrderHistoryService workOrderHistoryService;

    @Autowired
    UserPermissionService userPermissionService;

    @Autowired
    DeviceStateService deviceStateService;

    @Autowired
    BusinessNoticeService businessNoticeService;

    @Override
    public ConsumerDetailResponse consumerDetailAsst(CustDetailRequest request) {
        log.info("CustDetailRequest : {}", JSONObject.toJSONString(request));
        String spId = ApplicationUtils.getWorkingSpId();
        //本身以及下级spid
        List<String> spIds = organizationService.getSpIds(spId);

        //List<DictionaryItemRespDTO> equipmentManufacturerDTOList = holder.getDictionaryByKey(Constants.MANUFACTURER_CODE);
        //设备厂商名称
        ConsoleSkSupplierListResponse response = equipmentCmpService.supplierListRequest();
        log.info("调用厨房查询厂商接口返回：{}", response);
        List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
        if (response != null && response.getCode() == 0 && response.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(response.getData())) {
            supplierListVos = response.getData();
        }
        List<DictionaryItemRespDTO> equipmentTypeDTOList = holder.getDictionaryByKey(EquipmentType.DICT_CODE);
        ConsumerDetailResponse consumerDetailResponse = new ConsumerDetailResponse();

        // 查询 订单基本信息
        QueryWrapper<DtuBindingOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.lambda().eq(DtuBindingOrder::getOrderNo, request.getOrderNo())
                .eq(DtuBindingOrder::getMemberId, request.getMemberId())
                .in(DtuBindingOrder::getSpId, spIds)
                .eq(DtuBindingOrder::getIsDeleted, IS_DELETED_FALSE);
        //工单中多个设备,会有多条数据
        List<DtuBindingOrder> orderList = dtuBindingOrderMapper.selectList(orderQueryWrapper);
        DtuBindingOrder order = orderList.get(0);

        ConsumerResponse consumerResponse = new ConsumerResponse();
        consumerResponse.setId(order.getConsumerId());
        consumerResponse.setMemberId(request.getMemberId());
        consumerResponse.setContactsName(order.getCustName());
        consumerResponse.setContactsTelephone(order.getPhone());
        if (StringUtil.isNotEmpty(order.getRealAddress())) {
            consumerResponse.setInstallationAddress(order.getRealAddress());
        } else {
            consumerResponse.setInstallationAddress(order.getAddress());
        }
        List<Integer> consumerIds = new ArrayList<>();
        consumerIds.add(Integer.parseInt(request.getConsumerId()));
        List<Contacts> contacts=consumerMapper.selectLevelContactsByConsumerId(consumerIds);
        if (!CollectionUtils.isEmpty(contacts)){
            String telephone = contacts.get(0).getTelephone();
            consumerResponse.setLevelPhone(telephone);
        }
        QueryWrapper<Consumer> consumerWrapper = new QueryWrapper<>();
        consumerWrapper.lambda().eq(Consumer::getId, request.getConsumerId())
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Consumer::getSpId, spIds);
        Consumer consumer = consumerService.getOne(consumerWrapper);
        if (consumer == null) {
            throw new BizException("该客户id不存在!");
        }
        consumerResponse.setName(consumer.getName());
        consumerResponse.setCustomerAddress(consumer.getCustomerAddress());
        //客户的设备状态
        consumerResponse.setStatusAnyalert(false);
        consumerResponse.setStatusAnybroken(false);
        consumerResponse.setStatusAnyoffline(false);
        consumerResponse.setStatusAnynormal(true);

        //获取该工单下的所有设备
        List<ConsumerEquipmentResponse> equipmentVOList = new ArrayList<>();
        List<String> dtuIds = orderList.stream().map(DtuBindingOrder::getDeviceId).collect(Collectors.toList());
        List<Dtu> dtuList = equipmentService.listByIds(dtuIds);
        //查询设备信息,用户状态, 得到全量设备信息
        int sum = 0;
        for (Dtu dtu : dtuList) {
            LatestLog latestLog = latestLogService.get(dtu.getIMEI(), dtu.getSpId());
            //设备状态 0:离线 1:正常 2:低报 3:高报 4:故障 6:紫荆系统故障
            if (latestLog.getEquipmentStatus().equals(0)) {
                consumerResponse.setStatusAnyoffline(true);
                sum++;
            } else if (latestLog.getEquipmentStatus().equals(2) || latestLog.getEquipmentStatus().equals(3)
                    || latestLog.getEquipmentStatus().equals(6)) {
                consumerResponse.setStatusAnyalert(true);
            } else if (latestLog.getEquipmentStatus().equals(4)) {
                consumerResponse.setStatusAnybroken(true);
            }


            ConsumerEquipmentResponse vo = new ConsumerEquipmentResponse();
            BeanUtils.copyProperties(dtu, vo);
            vo.setValueExist(dtu.getValveInfoId()==0?1:0);
            vo.setEquipmentId(dtu.getDeviceCode());
            vo.setEquipmentTypeCode(dtu.getEquipmentType());
            DictionaryItemRespDTO equipmentTypeDTO = equipmentTypeDTOList.stream()
                    .filter(d -> d.getValue().equals(dtu.getEquipmentType()))
                    .collect(Collectors.toList()).get(0);
            AlarmSupplierListVo supplierListVo = supplierListVos.stream()
                    .filter(d -> d.getAlarmSystemCode().equals(dtu.getEquipmentManufacturer()))
                    .collect(Collectors.toList()).get(0);
            vo.setEquipmentType(equipmentTypeDTO.getName());
            vo.setEquipmentManufacturer(supplierListVo.getMsName());
            vo.setEquipmentModel(dtu.getEquipmentModel());
            vo.setEquipmentStatus(latestLog.getEquipmentStatus()); //设备状态
            //报警状态 需要附带浓度
            if (latestLog.getEquipmentStatus().equals(2) || latestLog.getEquipmentStatus().equals(3)) {
                latestLog.setEquipmentStatusInfo(latestLog.getEquipmentStatusInfo() + "(" + latestLog.getXlel() + ")");
            }

            if (latestLog.getValveStatus()!=null) vo.setValveStatus(latestLog.getValveStatus());
            if (latestLog.getReceiverStatus()!=null) vo.setReceiverStatus(latestLog.getReceiverStatus());
            vo.setValveStatus(ValveStatusEnum.parse(latestLog.getValveStatus()).getName());
            equipmentVOList.add(vo);

        }
        if (sum == dtuList.size()) {
            consumerResponse.setStatusAnynormal(false);
        }


        List<ConsumerEquipmentResponse> responseList = this.equipmentListByStatus(consumerResponse, equipmentVOList);
        //数据合并

        consumerDetailResponse.setConsumerResponse(consumerResponse);
        consumerDetailResponse.setConsumerEquipmentResponseList(responseList);

        return consumerDetailResponse;
    }


    @Override
    public ConsumerDetailResponse consumerDetailGas(CustDetailRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        //本身以及下级spid
        List<String> spIds = organizationService.getSpIds(spId);

        String consumerId = request.getConsumerId();
        ConsumerDetailResponse consumerDetailResponse = new ConsumerDetailResponse();
        //判断该客户是否存在
        QueryWrapper<Consumer> consumerWrapper = new QueryWrapper<>();
        consumerWrapper.lambda().eq(Consumer::getId, consumerId)
                .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Consumer::getSpId, spIds);
        Consumer consumer = consumerService.getOne(consumerWrapper);
        if (consumer == null) {
            throw new BizException("该客户id不存在!");
        }
        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }
        ConsumerResponse consumerResponse = new ConsumerResponse();
        BeanUtil.copyProperties(consumer, consumerResponse);
        //客户字典
        List<DictionaryItemRespDTO> dictionary = holder.getIndustryTypeZJ();
        for (DictionaryItemRespDTO dto : dictionary) {
            if (dto.getValue().equals(consumer.getIndustryType())) consumerResponse.setIndustryTypeName(dto.getName());
        }
        log.info("客户基本信息:{}", consumer.toString());

        List<Integer> consumerIds = new ArrayList<>();
        consumerIds.add(Integer.parseInt(consumerId));
        List<Contacts> contacts=consumerMapper.selectLevelContactsByConsumerId(consumerIds);
        if (!CollectionUtils.isEmpty(contacts)){
            String telephone = contacts.get(0).getTelephone();
            consumerResponse.setLevelPhone(telephone);
        }
        consumerResponse.setName(consumer.getName());
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(consumer.getOrgCode()) && orgSubsCodeMap.containsKey(consumer.getOrgCode())) {
            consumerResponse.setCompanyName(orgSubsCodeMap.get(consumer.getOrgCode()));
        } else {
            if (companyNameMap.containsKey(consumer.getSpId())) {
                consumerResponse.setCompanyName(companyNameMap.get(consumer.getSpId()));
            }
        }
        //客户的设备状态
        consumerResponse.setStatusAnyalert(false);
        consumerResponse.setStatusAnybroken(false);
        consumerResponse.setStatusAnyoffline(false);
        consumerResponse.setStatusAnynormal(true);
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getConsumerId, consumer.getId())
                .eq(Dtu::getIsDeleted, Constants.IS_DELETED_FALSE)
                .in(Dtu::getSpId, spIds);
        List<Dtu> dtuList = dtuMapper.selectList(dtuQueryWrapper);
        //字典转换
        //List<DictionaryItemRespDTO> equipmentManufacturerDTOList = holder.getDictionaryByKey(Constants.MANUFACTURER_CODE);
        //设备厂商名称
        ConsoleSkSupplierListResponse response = equipmentCmpService.supplierListRequest();
        log.info("调用厨房查询厂商接口返回：{}", response);
        List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
        if (response != null && response.getCode() == 0 && response.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(response.getData())) {
            supplierListVos = response.getData();
        }
        List<DictionaryItemRespDTO> equipmentTypeDTOList = holder.getDictionaryByKey(EquipmentType.DICT_CODE);
        List<ConsumerEquipmentResponse> equipmentVOList = new ArrayList<>();

        //查询设备信息,用户状态, 得到全量设备信息
        int sum = 0;
        for (Dtu dtu : dtuList) {
            log.info("设备："+dtu.toString());
            LatestLog latestLog = latestLogService.get(dtu.getIMEI(), dtu.getSpId());
            //设备状态 0:离线 1:正常 2:低报 3:高报 4:故障
            if (latestLog.getEquipmentStatus().equals(0)) {
                consumerResponse.setStatusAnyoffline(true);
                sum++;
            } else if (latestLog.getEquipmentStatus().equals(2) || latestLog.getEquipmentStatus().equals(3) ||
                    latestLog.getEquipmentStatus().equals(6)) {
                consumerResponse.setStatusAnyalert(true);
            } else if (latestLog.getEquipmentStatus().equals(4)) {
                consumerResponse.setStatusAnybroken(true);
            }


            ConsumerEquipmentResponse vo = new ConsumerEquipmentResponse();
            BeanUtils.copyProperties(dtu, vo);
            vo.setEquipmentName(dtu.getName());
            vo.setEquipmentId(dtu.getDeviceCode());
            vo.setEquipmentTypeCode(dtu.getEquipmentType());
            vo.setValueExist(dtu.getValveInfoId()==0?1:0);
            vo.setHasValve(dtu.getValveInfoId()==0?"-":"有");
            DictionaryItemRespDTO equipmentTypeDTO = equipmentTypeDTOList.stream()
                    .filter(d -> d.getValue().equals(dtu.getEquipmentType()))
                    .collect(Collectors.toList()).get(0);
            AlarmSupplierListVo supplierListVo = supplierListVos.stream()
                    .filter(d -> d.getAlarmSystemCode().equals(dtu.getEquipmentManufacturer()))
                    .collect(Collectors.toList()).get(0);
            vo.setEquipmentType(equipmentTypeDTO.getName());
            vo.setEquipmentManufacturer(supplierListVo != null? supplierListVo.getMsName() : "");
            vo.setEquipmentModel(dtu.getEquipmentModel());
            vo.setEquipmentModelMa(dtu.getEquipmentModel()+"("+ supplierListVo != null? supplierListVo.getMsName() : "" +")");
            vo.setEquipmentStatus(latestLog.getEquipmentStatus());
            vo.setEquipmentStatusName(DeviceStatusEnum.parse(latestLog.getEquipmentStatus()).getName()); //设备状态
            //报警状态 需要附带浓度
            if (latestLog.getEquipmentStatus().equals(2) || latestLog.getEquipmentStatus().equals(3) || latestLog.getEquipmentStatus().equals(6)) {
                latestLog.setEquipmentStatusInfo(latestLog.getEquipmentStatusInfo() + "(" + latestLog.getXlel() + ")");
            }
            vo.setEquipmentStatusInfo(latestLog.getEquipmentStatusInfo());
            vo.setEquipmentStatusAndInfo(vo.getEquipmentStatus()+"("+latestLog.getEquipmentStatusInfo()+")");
            if (latestLog.getValveStatus()!=null)
            vo.setValveStatus(ValveStatusEnum.parse(latestLog.getValveStatus()).getName());
            if (latestLog.getReceiverStatus()!=null) vo.setReceiverStatus(latestLog.getReceiverStatus()==0?"离线":"正常");
            //紫荆wifi报警的状态信息
            if ( Constants.ZJ_EQUIPMENT_FROM.equals(dtu.getEquipmentFrom()) ) {
                LambdaQueryWrapper<ReceiverValve> lqw = new LambdaQueryWrapper<>();
                lqw.eq(ReceiverValve::getDeviceId, dtu.getIMEI()).in(ReceiverValve::getSpId, spIds)
                        .eq(ReceiverValve::getIsDeleted, Constants.IS_DELETED_FALSE);
                ReceiverValve receiverValve = receiverValveService.getOne(lqw);
                if (receiverValve != null) {
                    vo.setWithReceiver(true);
                    vo.setReceiverStatus(receiverValve.getReceiverStatus()==0?"离线":"正常");
                    if (receiverValve.getBrokenStatus() == VALVE_WORK_STATUS_BROKEN){
                        vo.setValveStatus(ValveStatusEnum.parse(2).getName());
                    }else {
                        vo.setValveStatus(ValveStatusEnum.parse(receiverValve.getValveStatus()).getName());
                    }
                    vo.setBrokenInfo(receiverValve.getBrokenStatusInfo());
                }else{
                    vo.setWithReceiver(false);
                }
            }
            log.info("紫荆设备："+vo.toString());
            equipmentVOList.add(vo);
        }
        if (sum == dtuList.size()) {
            consumerResponse.setStatusAnynormal(false);
        }

        List<ConsumerEquipmentResponse> responseList = this.equipmentListByStatus(consumerResponse, equipmentVOList);
        log.info("设备列表："+responseList.toString());
        //数据合并
        consumerDetailResponse.setConsumerResponse(consumerResponse);
        consumerDetailResponse.setConsumerEquipmentResponseList(responseList);

        return consumerDetailResponse;
    }

    @Override
    public List<ConsumerEquipmentResponse> equipmentListByStatus(ConsumerResponse consumerResponse, List<ConsumerEquipmentResponse> equipmentVOList) {
        //设备状态 0:离线 1:正常 2:低报 3:高报 4:故障
        //存在报警
        //todo
        List<ConsumerEquipmentResponse> list = new ArrayList<>();
        //不正常的设备都展示
        if (consumerResponse.getStatusAnyalert()) {
            for (ConsumerEquipmentResponse equipment : equipmentVOList) {
//                equipment.setEquipmentStatus(DeviceStatusEnum
//                        .parse(Integer.parseInt(equipment.getEquipmentStatus()+"")).getName());
                if (equipment.getEquipmentStatus().equals(3)) {
                    list.add(equipment);
                }
                if (equipment.getEquipmentStatus().equals(2)) {
                    list.add(equipment);
                }
                if (equipment.getEquipmentStatus().equals(4)) {
                    list.add(equipment);
                }
                if (equipment.getEquipmentStatus().equals(0)) {
                    list.add(equipment);
                }
                if (equipment.getEquipmentStatus().equals(6)) {
                    list.add(equipment);
                }
            }

            //存在故障
        } else if (consumerResponse.getStatusAnybroken()) {
            for (ConsumerEquipmentResponse equipment : equipmentVOList) {
                if (equipment.getEquipmentStatus().equals(4)) {
                    list.add(equipment);
                }
            }
            for (ConsumerEquipmentResponse equipment : equipmentVOList) {
                if (equipment.getEquipmentStatus().equals(0)) {
                    list.add(equipment);
                }
            }
            // 存在离线
        } else if (consumerResponse.getStatusAnyoffline()) {
            for (ConsumerEquipmentResponse equipment : equipmentVOList) {
                if (equipment.getEquipmentStatus().equals(1)) {
                    list.add(equipment);
                }
            }
            for (ConsumerEquipmentResponse equipment : equipmentVOList) {
                if (equipment.getEquipmentStatus().equals(0)) {
                    list.add(equipment);
                }
            }
        } else if (consumerResponse.getStatusAnynormal()) {
            list = equipmentVOList;
        }

        return list;
    }

    @Override
    public List<ConsumerDetailResponse> warningInfoAsst(Integer templateType,Integer applyStatus) {
        String spId = ApplicationUtils.getWorkingSpId();
        //本身以及下级spid
        List<String> spIds = organizationService.getSpIds(spId);
        //字典转换
        //List<DictionaryItemRespDTO> equipmentManufacturerDTOList = holder.getDictionaryByKey(Constants.MANUFACTURER_CODE);
        List<DictionaryItemRespDTO> equipmentTypeDTOList = holder.getDictionaryByKey(EquipmentType.DICT_CODE);
        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }

        LatestLogListVO vo = new LatestLogListVO();
        vo.setSpIds(spIds);
        vo.setPage(1);
        vo.setPageSize(30);
        vo.setApplyStatus1(applyStatus==3?2:applyStatus);
        List<Integer> consumerIds = new ArrayList<>();
        //报警信息
        List<HistoryAlarmVo> list = historyAlarmMapper.getRecordWithType2(vo);
        log.info("warningInfoAsst-list:{}",JSONObject.toJSONString(list));
        if (!CollectionUtils.isEmpty(list)) list.forEach(historyAlarmVo ->consumerIds.add(historyAlarmVo.getConsumerId()));
        //故障信息
        List<HistoryBrokenVO> brokenVOList = historyBrokenMapper.getRecordWithType2(vo);
        log.info("warningInfoAsst-brokenVOList:{}",JSONObject.toJSONString(brokenVOList));
        if (!CollectionUtils.isEmpty(brokenVOList))
            list.forEach(historyAlarmVo -> consumerIds.add(historyAlarmVo.getConsumerId()));
        Map<Integer, List<Contacts>> contactsMap =new HashMap<>();
        if (!CollectionUtils.isEmpty(consumerIds)){
           List<Contacts> contacts=consumerMapper.selectLevelContactsByConsumerId(consumerIds);
            contactsMap = contacts.stream().
                    collect(Collectors.groupingBy(Contacts::getConsumerId, Collectors.toList()));
            log.info("warningInfoAsst-contactsMap:{}",JSONObject.toJSONString(contactsMap));
        }
        List<ConsumerDetailResponse> responseList = new ArrayList<>();
        for (HistoryAlarmVo historyAlarmVo : list) {
            String equipmentManufacturerCode = String.valueOf(historyAlarmVo.getEquipmentManufacturer());
            String equipmentTypeCode = String.valueOf(historyAlarmVo.getEquipmentType());
            //客户信息
            ConsumerDetailResponse response = new ConsumerDetailResponse();
            //设备信息
            ConsumerResponse consumerResponse = new ConsumerResponse();
            ConsumerEquipmentResponse equipmentResponse = new ConsumerEquipmentResponse();
            List<DictionaryItemRespDTO> equipmentTypeDTOs = equipmentTypeDTOList.stream()
                    .filter(d -> d.getValue().equals(equipmentTypeCode))
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(equipmentTypeDTOs)){
                equipmentResponse.setEquipmentType(equipmentTypeDTOs.get(0).getName());
            }

            List<DictionaryItemRespDTO> equipmentManufacturerDTOs = equipmentTypeDTOList.stream()
                    .filter(d -> d.getValue().equals(equipmentManufacturerCode))
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(equipmentManufacturerDTOs)){
                equipmentResponse.setEquipmentManufacturer(equipmentManufacturerDTOs.get(0).getName());
            }
            response.setLastTime(historyAlarmVo.getLatestTime());

            consumerResponse.setLevelPhone(contactsMap.get(historyAlarmVo.getConsumerId())!=null
                    ?contactsMap.get(historyAlarmVo.getConsumerId()).get(0).getTelephone():"");
            consumerResponse.setName(historyAlarmVo.getName());
            consumerResponse.setId(historyAlarmVo.getConsumerId());
            consumerResponse.setMemberId(historyAlarmVo.getMemberId());
            consumerResponse.setContactsName(historyAlarmVo.getContactName());
            consumerResponse.setContactsTelephone(historyAlarmVo.getContactPhone());
            consumerResponse.setPhone(historyAlarmVo.getPhone());
            consumerResponse.setCustomerAddress(historyAlarmVo.getCustomerAddress());
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(historyAlarmVo.getOrgCode()) && orgSubsCodeMap.containsKey(historyAlarmVo.getOrgCode())) {
                consumerResponse.setCompanyName(orgSubsCodeMap.get(historyAlarmVo.getOrgCode()));
            } else {
                if (companyNameMap.containsKey(historyAlarmVo.getSpId())) {
                    consumerResponse.setCompanyName(companyNameMap.get(historyAlarmVo.getSpId()));
                }
            }
            equipmentResponse.setId(historyAlarmVo.getId()+"");
            equipmentResponse.setIMEI(historyAlarmVo.getImei());
            equipmentResponse.setInstallationPosition(historyAlarmVo.getInstallationPosition());
            equipmentResponse.setEquipmentModel(historyAlarmVo.getEquipmentModel());
            equipmentResponse.setEquipmentStatus(2);
            equipmentResponse.setXLEL(String.valueOf(historyAlarmVo.getConcentration())+"%LEL");
            equipmentResponse.setInstallationAddress(historyAlarmVo.getInstallationAddress());
            equipmentResponse.setEquipmentFrom(historyAlarmVo.getEquipmentFrom());
            equipmentResponse.setAppealResult(historyAlarmVo.getAppealResult());
            equipmentResponse.setApplyStatus(historyAlarmVo.getApplyStatus());
            equipmentResponse.setOrderCompleteTime(historyAlarmVo.getOrderCompleteTime());
            equipmentResponse.setOrderCreatedTime(historyAlarmVo.getOrderCreatedTime());
            equipmentResponse.setOrderNo(historyAlarmVo.getOrderNo());
            equipmentResponse.setValueExist(StringUtils.isEmpty(historyAlarmVo.getValveInfoId())
                    ||historyAlarmVo.getValveInfoId()==0?1:0);
            if ( equipmentResponse.getEquipmentFrom() == Constants.ZJ_EQUIPMENT_FROM) {
                LambdaQueryWrapper<ReceiverValve> lqw = new LambdaQueryWrapper<>();
                lqw.eq(ReceiverValve::getDeviceId, equipmentResponse.getIMEI()).eq(ReceiverValve::getSpId, historyAlarmVo.getSpId())
                        .eq(ReceiverValve::getIsDeleted, Constants.IS_DELETED_FALSE);
                ReceiverValve receiverValve = receiverValveService.getOne(lqw);
                if (receiverValve != null) {

                    equipmentResponse.setWithReceiver(true);
                    equipmentResponse.setReceiverStatus(historyAlarmVo.getReceiverStatus()==0?"离线":"正常");
                    equipmentResponse.setValveStatus(ValveStatusEnum.parse(historyAlarmVo.getValveStatus()).getName());
                    equipmentResponse.setBrokenInfo(historyAlarmVo.getBrokenInfo());
                    equipmentResponse.setBrokenStatus(historyAlarmVo.getBrokenStatus());
                }else{
                    equipmentResponse.setWithReceiver(false);
                }
            }
            List<ConsumerEquipmentResponse> equipmentResponseList = new ArrayList<>();
            equipmentResponseList.add(equipmentResponse);
            response.setConsumerResponse(consumerResponse);
            response.setConsumerEquipmentResponseList(equipmentResponseList);
            responseList.add(response);
        }
        log.info("warningInfoAsst-responseList:{}",JSONObject.toJSONString(responseList));
        for (HistoryBrokenVO historyBrokenVO : brokenVOList) {
            String equipmentManufacturerCode = String.valueOf(historyBrokenVO.getEquipmentManufacturer());
            String equipmentTypeCode = String.valueOf(historyBrokenVO.getEquipmentType());

            ConsumerDetailResponse response = new ConsumerDetailResponse();
            ConsumerResponse consumerResponse = new ConsumerResponse();
            ConsumerEquipmentResponse equipmentResponse = new ConsumerEquipmentResponse();

            List<DictionaryItemRespDTO> equipmentTypeDTOs = equipmentTypeDTOList.stream()
                    .filter(d -> d.getValue().equals(equipmentTypeCode))
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(equipmentTypeDTOs)){
                equipmentResponse.setEquipmentType(equipmentTypeDTOs.get(0).getName());
            }

            List<DictionaryItemRespDTO> equipmentManufacturerDTOs = equipmentTypeDTOList.stream()
                    .filter(d -> d.getValue().equals(equipmentManufacturerCode))
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(equipmentManufacturerDTOs)){
                equipmentResponse.setEquipmentManufacturer(equipmentManufacturerDTOs.get(0).getName());
            }

            response.setLastTime(historyBrokenVO.getLatestTime());
            consumerResponse.setLevelPhone(contactsMap.get(historyBrokenVO.getConsumerId())!=null?
                    contactsMap.get(historyBrokenVO.getConsumerId()).get(0).getTelephone():"");
            consumerResponse.setName(historyBrokenVO.getName());
            consumerResponse.setId(historyBrokenVO.getConsumerId());
            consumerResponse.setMemberId(historyBrokenVO.getMemberId());
            consumerResponse.setContactsName(historyBrokenVO.getContactName());
            consumerResponse.setContactsTelephone(historyBrokenVO.getContactPhone());
            consumerResponse.setPhone(historyBrokenVO.getPhone());
            consumerResponse.setCustomerAddress(historyBrokenVO.getCustomerAddress());
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(historyBrokenVO.getOrgCode()) && orgSubsCodeMap.containsKey(historyBrokenVO.getOrgCode())) {
                consumerResponse.setCompanyName(orgSubsCodeMap.get(historyBrokenVO.getOrgCode()));
            } else {
                if (companyNameMap.containsKey(historyBrokenVO.getSpId())) {
                    consumerResponse.setCompanyName(companyNameMap.get(historyBrokenVO.getSpId()));
                }
            }
            equipmentResponse.setId(historyBrokenVO.getId()+"");
            equipmentResponse.setIMEI(historyBrokenVO.getImei());
            equipmentResponse.setInstallationPosition(historyBrokenVO.getInstallationPosition());
            equipmentResponse.setEquipmentModel(historyBrokenVO.getEquipmentModel());
            equipmentResponse.setEquipmentStatus(4);  //故障
            equipmentResponse.setBrokenReason(historyBrokenVO.getBrokenReason());
            equipmentResponse.setInstallationAddress(historyBrokenVO.getInstallationAddress());
            equipmentResponse.setEquipmentFrom(historyBrokenVO.getEquipmentFrom());
            equipmentResponse.setAppealResult(historyBrokenVO.getAppealResult());
            equipmentResponse.setApplyStatus(historyBrokenVO.getApplyStatus());
            equipmentResponse.setOrderCompleteTime(historyBrokenVO.getOrderCompleteTime());
            equipmentResponse.setOrderCreatedTime(historyBrokenVO.getOrderCreatedTime());
            equipmentResponse.setOrderNo(historyBrokenVO.getOrderNo());
            equipmentResponse.setValueExist(StringUtils.isEmpty(historyBrokenVO.getValveInfoId())
                    ||historyBrokenVO.getValveInfoId()==0?1:0);
            if ( equipmentResponse.getEquipmentFrom() == Constants.ZJ_EQUIPMENT_FROM) {
                LambdaQueryWrapper<ReceiverValve> lqw = new LambdaQueryWrapper<>();
                lqw.eq(ReceiverValve::getDeviceId, equipmentResponse.getIMEI()).eq(ReceiverValve::getSpId, historyBrokenVO.getSpId())
                        .eq(ReceiverValve::getIsDeleted, Constants.IS_DELETED_FALSE);
                ReceiverValve receiverValve = receiverValveService.getOne(lqw);
                if (receiverValve != null) {
                    equipmentResponse.setWithReceiver(true);
                    equipmentResponse.setReceiverStatus(historyBrokenVO.getReceiverStatus()==0?"离线":"正常");
                    equipmentResponse.setValveStatus(ValveStatusEnum.parse(historyBrokenVO.getValveStatus()).getName());
                    equipmentResponse.setBrokenInfo(historyBrokenVO.getBrokenInfo());
                    equipmentResponse.setBrokenStatus(historyBrokenVO.getBrokenStatus());
                }else{
                    equipmentResponse.setWithReceiver(false);
                }
            }

            List<ConsumerEquipmentResponse> equipmentResponseList = new ArrayList<>();
            equipmentResponseList.add(equipmentResponse);
            response.setConsumerResponse(consumerResponse);
            response.setConsumerEquipmentResponseList(equipmentResponseList);
            responseList.add(response);
        }
        log.info("warningInfoAsst-responseList:{}",JSONObject.toJSONString(responseList));
        //取列表时间倒序30条
        responseList.sort((t1,t2) -> t2.getLastTime().compareTo(t1.getLastTime()));
        int size = responseList.size();
        int end = 30;
        if ( size < 30) end = size;
        List<ConsumerDetailResponse> data = responseList.subList(0, end);
        return data;
    }

    @Override
    public List<ConsumerDetailResponse> warningInfoGas(Integer templateType, Integer applyStatus, Integer dataType,String timeStart,String timeEnd) {
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        //字典转换
        //List<DictionaryItemRespDTO> equipmentManufacturerDTOList = holder.getDictionaryByKey(Constants.MANUFACTURER_CODE);
        //设备厂商名称
        ConsoleSkSupplierListResponse listResponse = equipmentCmpService.supplierListRequest();
        log.info("调用厨房查询厂商接口返回：{}", listResponse);
        List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
        if (listResponse != null && listResponse.getCode() == 0 && listResponse.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(listResponse.getData())) {
            supplierListVos = listResponse.getData();
        }
        List<DictionaryItemRespDTO> equipmentTypeDTOList = holder.getDictionaryByKey(EquipmentType.DICT_CODE);

        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }
        LatestLogListVO vo = new LatestLogListVO();
        vo.setSpIds(spIds);
        vo.setPage(1);
        vo.setPageSize(30);
        if (dataType==1)vo.setPageSize(100);
        vo.setApplyStatus1(applyStatus==3?2:applyStatus);
        vo.setTimeStart(timeStart);
        vo.setTimeEnd(timeEnd);
        //报警信息
        Page<Object> page = PageHelper.startPage(1, 30);
        List<Integer> consumerIds = new ArrayList<>();
        List<HistoryAlarmVo> alarmVoList = historyAlarmMapper.getRecordWithType1(vo);
        log.info("warningInfoGas-alarmVoList:{}",JSONObject.toJSONString(alarmVoList));
        if (!CollectionUtils.isEmpty(alarmVoList))
            alarmVoList.forEach(historyAlarmVo -> consumerIds.add(historyAlarmVo.getConsumerId()));
        //获取所有imei号, 判断这些设备是否具有 接收器/电磁阀
        List<ReceiverValve> alarmValveList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(alarmVoList)){
            List<String> alarmImeiList = alarmVoList.stream().map(HistoryAlarmVo::getImei).collect(Collectors.toList());
            QueryWrapper<ReceiverValve> valveQueryWrapper1 = new QueryWrapper<>();
            valveQueryWrapper1.lambda().eq(ReceiverValve::getIsDeleted, IS_DELETED_FALSE)
                    .in(ReceiverValve::getDeviceId,alarmImeiList);
            alarmValveList= receiverValveService.list(valveQueryWrapper1);

        }
        Map<String, ReceiverValve> receiverValveMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(alarmValveList)) {
            receiverValveMap = alarmValveList.stream().collect(Collectors.toMap(ReceiverValve::getDeviceId, ReceiverValve -> ReceiverValve, (a1, a2) -> a2));
        }
        Map<Integer, List<Contacts>> contactsMap =new HashMap<>();
        if (!CollectionUtils.isEmpty(consumerIds)){
            List<Contacts> contacts=consumerMapper.selectLevelContactsByConsumerId(consumerIds);
            contactsMap = contacts.stream().
                    collect(Collectors.groupingBy(Contacts::getConsumerId, Collectors.toList()));
            log.info("warningInfoAsst-contactsMap:{}",JSONObject.toJSONString(contactsMap));
        }
        List<ConsumerDetailResponse> responseList = new ArrayList<>();
        List<DictionaryItemRespDTO> dictionary = holder.getIndustryTypeZJ();
        Map<String, String> dictionaryMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(dictionary)) {
            dictionaryMap = dictionary.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getValue, DictionaryItemRespDTO::getName, (a1, a2) -> a2));
        }
        for (HistoryAlarmVo historyAlarmVo : alarmVoList) {
            String equipmentManufacturerCode = String.valueOf(historyAlarmVo.getEquipmentManufacturer());
            String equipmentTypeCode = String.valueOf(historyAlarmVo.getEquipmentType());
            String equipmentTypeName = "";
            if( !StringUtils.isEmpty(equipmentTypeCode) ){
                List<DictionaryItemRespDTO> equipmentTypeList = equipmentTypeDTOList.stream()
                        .filter(d -> d.getValue().equals(equipmentTypeCode))
                        .collect(Collectors.toList());
                if(null!=equipmentTypeList && !equipmentTypeList.isEmpty()){
                    equipmentTypeName = equipmentTypeList.get(0).getName();
                }
            }

            String equipmentManufacturerName = "";
            if( !StringUtils.isEmpty(equipmentManufacturerCode) ){
                List<AlarmSupplierListVo> listVos = supplierListVos.stream()
                        .filter(d -> d.getAlarmSystemCode().equals(equipmentManufacturerCode))
                        .collect(Collectors.toList());
                if(null!=listVos && !listVos.isEmpty()){
                    equipmentManufacturerName = listVos.get(0).getMsName();
                }
            }

            ConsumerDetailResponse response = new ConsumerDetailResponse();
            ConsumerResponse consumerResponse = new ConsumerResponse();
            ConsumerEquipmentResponse equipmentResponse = new ConsumerEquipmentResponse();

            response.setLastTime(historyAlarmVo.getLatestTime());
            consumerResponse.setLevelPhone(contactsMap.get(historyAlarmVo.getConsumerId())!=null?
                    contactsMap.get(historyAlarmVo.getConsumerId()).get(0).getTelephone():"");
            consumerResponse.setName(historyAlarmVo.getName());
            consumerResponse.setId(historyAlarmVo.getConsumerId());
            consumerResponse.setSubsCode(historyAlarmVo.getSubsCode());
            consumerResponse.setCustName(historyAlarmVo.getCustName());
            consumerResponse.setCustAddress(historyAlarmVo.getCustAddress());
            consumerResponse.setMemberId(historyAlarmVo.getMemberId());
            consumerResponse.setPhone(historyAlarmVo.getPhone());
            consumerResponse.setCustPhone(historyAlarmVo.getCustPhone());
            consumerResponse.setSubsCodeName(consumerResponse.getCustName()+"("+consumerResponse.getSubsCode()+")");
            consumerResponse.setCustType(historyAlarmVo.getCustType());
            consumerResponse.setCustomerAddress(historyAlarmVo.getCustomerAddress());

            Consumer custTypeParam = new Consumer();
            custTypeParam.setId(historyAlarmVo.getConsumerId());
            custTypeParam.setSubsCode(historyAlarmVo.getSubsCode());
            custTypeParam.setCustTypeCode(historyAlarmVo.getCustTypeCode());
            custTypeParam.setSpId(spId);
            consumerResponse.setOrderCustType(workOrderHistoryService.getOrderLaunchCustType(custTypeParam));

            if (org.apache.commons.lang3.StringUtils.isNotEmpty(historyAlarmVo.getOrgCode()) && orgSubsCodeMap.containsKey(historyAlarmVo.getOrgCode())) {
                consumerResponse.setCompanyName(orgSubsCodeMap.get(historyAlarmVo.getOrgCode()));
            } else {
                if (companyNameMap.containsKey(historyAlarmVo.getSpId())) {
                    consumerResponse.setCompanyName(companyNameMap.get(historyAlarmVo.getSpId()));
                }
            }
            if (dictionaryMap.containsKey(historyAlarmVo.getIndustryType())){
                consumerResponse.setIndustryTypeName(dictionaryMap.get(historyAlarmVo.getIndustryType()));
            }
            if (receiverValveMap.containsKey(historyAlarmVo.getImei())){
                equipmentResponse.setWithReceiver(true);
            }
            BeanUtils.copyProperties(historyAlarmVo, equipmentResponse);
            equipmentResponse.setEquipmentManufacturer(equipmentManufacturerName);
            String equipmentModelMa = "";
            if( !StringUtils.isEmpty(historyAlarmVo.getEquipmentModel()) ){
                equipmentModelMa = historyAlarmVo.getEquipmentModel();
            }
            if( !StringUtils.isEmpty(equipmentManufacturerName)){
                equipmentModelMa += "（"+equipmentManufacturerName+"）";
            }
            equipmentResponse.setEquipmentModelMa(equipmentModelMa);
            equipmentResponse.setId(historyAlarmVo.getId()+"");
            equipmentResponse.setIMEI(historyAlarmVo.getImei());
            equipmentResponse.setXLEL(String.valueOf(historyAlarmVo.getConcentration())+"%LEL");
            equipmentResponse.setSignal(SignalEnum.getName(historyAlarmVo.getSignal()));
            equipmentResponse.setEquipmentType(historyAlarmVo.getEquipmentType());
            equipmentResponse.setEquipmentTypeName(equipmentTypeName);
            equipmentResponse.setEquipmentStatus(2);
            equipmentResponse.setEquipmentStatusName(DeviceStatusEnum.parse(2).getName());
            equipmentResponse.setEquipmentStatusAndInfo(equipmentResponse.getEquipmentStatusName()+"(设备报警)");
            equipmentResponse.setEquipmentStatusInfo("设备报警");
            equipmentResponse.setBrokenInfo(historyAlarmVo.getBrokenInfo());
            equipmentResponse.setReceiverStatus(StringUtils.isEmpty(historyAlarmVo.getReceiverStatus())||
                    historyAlarmVo.getReceiverStatus()==0?"离线":"正常");
            equipmentResponse.setValveStatus(ValveStatusEnum.parse(historyAlarmVo.getValveStatus()).getName());
            equipmentResponse.setBrokenStatus(historyAlarmVo.getBrokenStatus());
            equipmentResponse.setEquipmentFrom(historyAlarmVo.getEquipmentFrom());
            equipmentResponse.setAppealResult(historyAlarmVo.getAppealResult());
            equipmentResponse.setApplyStatus(historyAlarmVo.getApplyStatus());
            equipmentResponse.setOrderCompleteTime(historyAlarmVo.getOrderCompleteTime());
            equipmentResponse.setOrderCreatedTime(historyAlarmVo.getOrderCreatedTime());
            equipmentResponse.setOrderNo(historyAlarmVo.getOrderNo());
            equipmentResponse.setValueExist(StringUtils.isEmpty(historyAlarmVo.getValveInfoId())
                    ||historyAlarmVo.getValveInfoId()==0?1:0);
            List<ConsumerEquipmentResponse> equipmentResponseList = new ArrayList<>();
            equipmentResponseList.add(equipmentResponse);
            response.setConsumerResponse(consumerResponse);
            response.setConsumerEquipmentResponseList(equipmentResponseList);
            responseList.add(response);
        }

        if (dataType==0){
            //故障信息
            Page<Object> page1 = PageHelper.startPage(1, 30);
            //获取所有imei号, 判断这些设备是否具有 接收器/电磁阀
            List<HistoryBrokenVO> brokenVOList = historyBrokenMapper.getRecordWithType1(vo);
            log.info("warningInfoAsst-brokenVOList:{}",JSONObject.toJSONString(brokenVOList));
            if (!CollectionUtils.isEmpty(brokenVOList))
                brokenVOList.forEach(historyAlarmVo -> consumerIds.add(historyAlarmVo.getConsumerId()));
            if (!CollectionUtils.isEmpty(consumerIds)){
                List<Contacts> contacts=consumerMapper.selectLevelContactsByConsumerId(consumerIds);
                contactsMap = contacts.stream().
                        collect(Collectors.groupingBy(Contacts::getConsumerId, Collectors.toList()));
                log.info("warningInfoAsst-contactsMap:{}",JSONObject.toJSONString(contactsMap));
            }
            List<ReceiverValve>  brokenValveList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(brokenVOList)){
                List<String> brokenImeiList = brokenVOList.stream().map(HistoryBrokenVO::getImei).collect(Collectors.toList());
                QueryWrapper<ReceiverValve> valveQueryWrapper1 = new QueryWrapper<>();
                valveQueryWrapper1.lambda().eq(ReceiverValve::getIsDeleted, IS_DELETED_FALSE)
                        .in(ReceiverValve::getDeviceId,brokenImeiList);
                brokenValveList = receiverValveService.list(valveQueryWrapper1);
            }
            Map<String, ReceiverValve> stringReceiverValveMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(brokenValveList)) {
                stringReceiverValveMap = brokenValveList.stream().collect(Collectors.toMap(ReceiverValve::getDeviceId, ReceiverValve -> ReceiverValve, (a1, a2) -> a2));
            }

            for (HistoryBrokenVO historyBrokenVO : brokenVOList) {
                String equipmentManufacturerCode = String.valueOf(historyBrokenVO.getEquipmentManufacturer());
                String equipmentTypeCode = String.valueOf(historyBrokenVO.getEquipmentType());

                String equipmentTypeName = "";
                if( !StringUtils.isEmpty(equipmentTypeCode) ){
                    List<DictionaryItemRespDTO> equipmentTypeList = equipmentTypeDTOList.stream()
                            .filter(d -> d.getValue().equals(equipmentTypeCode))
                            .collect(Collectors.toList());
                    if(null!=equipmentTypeList && !equipmentTypeList.isEmpty()){
                        equipmentTypeName = equipmentTypeList.get(0).getName();
                    }
                }

                String equipmentManufacturerName = "";
                if( !StringUtils.isEmpty(equipmentManufacturerCode) ){
                    List<AlarmSupplierListVo> listVos = supplierListVos.stream()
                            .filter(d -> d.getAlarmSystemCode().equals(equipmentManufacturerCode))
                            .collect(Collectors.toList());
                    if(null!=listVos && !listVos.isEmpty()){
                        equipmentManufacturerName = listVos.get(0).getMsName();
                    }
                }

                ConsumerDetailResponse response = new ConsumerDetailResponse();
                ConsumerResponse consumerResponse = new ConsumerResponse();
                ConsumerEquipmentResponse equipmentResponse = new ConsumerEquipmentResponse();

                response.setLastTime(historyBrokenVO.getLatestTime());
                equipmentResponse.setIMEI(historyBrokenVO.getImei());
                    consumerResponse.setLevelPhone(contactsMap.get(historyBrokenVO.getConsumerId())==null?"":
                            contactsMap.get(historyBrokenVO.getConsumerId()).get(0).getTelephone());
                consumerResponse.setName(historyBrokenVO.getName());
                consumerResponse.setId(historyBrokenVO.getConsumerId());
                consumerResponse.setSubsCode(historyBrokenVO.getSubsCode());
                consumerResponse.setCustName(historyBrokenVO.getCustName());
                consumerResponse.setCustAddress(historyBrokenVO.getCustAddress());
                consumerResponse.setMemberId(historyBrokenVO.getMemberId());
                consumerResponse.setPhone(historyBrokenVO.getPhone());
                consumerResponse.setCustPhone(historyBrokenVO.getCustPhone());
                consumerResponse.setCustType(historyBrokenVO.getCustType());
                consumerResponse.setSubsCodeName(consumerResponse.getCustName()+"("+consumerResponse.getSubsCode()+")");
                consumerResponse.setCustomerAddress(historyBrokenVO.getCustomerAddress());

                Consumer custTypeParam = new Consumer();
                custTypeParam.setId(historyBrokenVO.getConsumerId());
                custTypeParam.setSubsCode(historyBrokenVO.getSubsCode());
                custTypeParam.setCustTypeCode(historyBrokenVO.getCustTypeCode());
                custTypeParam.setSpId(spId);
                consumerResponse.setOrderCustType(workOrderHistoryService.getOrderLaunchCustType(custTypeParam));

                if (org.apache.commons.lang3.StringUtils.isNotEmpty(historyBrokenVO.getOrgCode()) && orgSubsCodeMap.containsKey(historyBrokenVO.getOrgCode())) {
                    consumerResponse.setCompanyName(orgSubsCodeMap.get(historyBrokenVO.getOrgCode()));
                } else {
                    if (companyNameMap.containsKey(historyBrokenVO.getSpId())) {
                        consumerResponse.setCompanyName(companyNameMap.get(historyBrokenVO.getSpId()));
                    }
                }
                if (dictionaryMap.containsKey(historyBrokenVO.getIndustryType())) {
                    consumerResponse.setIndustryTypeName(dictionaryMap.get(historyBrokenVO.getIndustryType()));
                }
                equipmentResponse.setValueExist(StringUtils.isEmpty(historyBrokenVO.getValveInfoId())
                        ||historyBrokenVO.getValveInfoId()==0?1:0);

                if (stringReceiverValveMap.containsKey(historyBrokenVO.getImei())){
                    equipmentResponse.setWithReceiver(true);
                }

                BeanUtils.copyProperties(historyBrokenVO, equipmentResponse);
                equipmentResponse.setId(historyBrokenVO.getId()+"");
                equipmentResponse.setEquipmentType(equipmentTypeName);
                equipmentResponse.setEquipmentManufacturer(equipmentManufacturerName);
                String equipmentModelMa = "";
                if( !StringUtils.isEmpty(historyBrokenVO.getEquipmentModel()) ){
                    equipmentModelMa = historyBrokenVO.getEquipmentModel();
                }
                if( !StringUtils.isEmpty(equipmentManufacturerName)){
                    equipmentModelMa += "（"+equipmentManufacturerName+"）";
                }
                equipmentResponse.setEquipmentModelMa(equipmentModelMa);
                equipmentResponse.setEquipmentStatus(4);
                equipmentResponse.setXLEL(String.valueOf(historyBrokenVO.getConcentration())+"%LEL");
                equipmentResponse.setSignal(SignalEnum.getName(historyBrokenVO.getSignal()));
                equipmentResponse.setEquipmentStatusName(DeviceStatusEnum.parse(4).getName());
                equipmentResponse.setEquipmentStatusAndInfo(equipmentResponse.getEquipmentStatusName()+"(设备故障)");
                equipmentResponse.setEquipmentStatusInfo("设备故障");
                equipmentResponse.setBrokenReason(historyBrokenVO.getBrokenReason());
                equipmentResponse.setBrokenInfo(historyBrokenVO.getBrokenInfo());
                equipmentResponse.setReceiverStatus(StringUtils.isEmpty(historyBrokenVO.getReceiverStatus())||historyBrokenVO.getReceiverStatus()==0?"离线":"正常");
                equipmentResponse.setValveStatus(ValveStatusEnum.parse(historyBrokenVO.getValveStatus()).getName());
                equipmentResponse.setBrokenStatus(historyBrokenVO.getBrokenStatus());
                equipmentResponse.setEquipmentFrom(historyBrokenVO.getEquipmentFrom());
                equipmentResponse.setValueExist(StringUtils.isEmpty(historyBrokenVO.getValveInfoId())
                        ||historyBrokenVO.getValveInfoId()==0?1:0);
                equipmentResponse.setHasValve(StringUtils.isEmpty(historyBrokenVO.getValveInfoId())||
                        historyBrokenVO.getValveInfoId()==0?"-":"有");
                equipmentResponse.setAppealResult(historyBrokenVO.getAppealResult());
                equipmentResponse.setApplyStatus(historyBrokenVO.getApplyStatus());
                equipmentResponse.setOrderCompleteTime(historyBrokenVO.getOrderCompleteTime());
                equipmentResponse.setOrderCreatedTime(historyBrokenVO.getOrderCreatedTime());
                equipmentResponse.setOrderNo(historyBrokenVO.getOrderNo());
                List<ConsumerEquipmentResponse> equipmentResponseList = new ArrayList<>();
                equipmentResponseList.add(equipmentResponse);
                response.setConsumerResponse(consumerResponse);
                response.setConsumerEquipmentResponseList(equipmentResponseList);
                responseList.add(response);
            }

        }

        log.info("warningInfoGas-responseList：{}",JSONObject.toJSON(responseList));
        //取列表时间倒序30条
        responseList.sort((t1,t2) -> t2.getLastTime().compareTo(t1.getLastTime()));
        int size = responseList.size();
        int end = 30;
        if ( size < 30) end = size;
        List<ConsumerDetailResponse> data = responseList.subList(0, end);
        return data;
    }

    /**
     * 设备运行情况
     *
     * @return
     */
    @Override
    public EquipmentRunningResponse equipmentRunningInfo() {
        EquipmentRunningResponse result = new EquipmentRunningResponse();
        String spId = ApplicationUtils.getWorkingSpId();
        //本身以及下级spid
        List<String> spIds = organizationService.getSpIds(spId);
        List<EquipmentVo> datas = dtuMapper.selectEquipmentBySpIds(spIds);
        log.info("equipmentRunningInfo-datas-size:{}", datas.size());
        if (!CollectionUtil.isEmpty(datas)) {
            datas.forEach(equipmentVo -> {
                if (equipmentVo.getDeviceStatus() == null) equipmentVo.setDeviceStatus(0);
            });
            List<EquipmentVo> offline = datas.stream().filter(equipmentVo -> {
                return equipmentVo.getDeviceStatus() == null || equipmentVo.getDeviceStatus() == 0;
            }).collect(Collectors.toList());
            List<EquipmentVo> normal = datas.stream().filter(equipmentVo -> {
                return equipmentVo.getDeviceStatus() == 1;
            }).collect(Collectors.toList());
            List<EquipmentVo> warning = datas.stream().filter(equipmentVo -> {
                return equipmentVo.getDeviceStatus() == 2 || equipmentVo.getDeviceStatus() == 3
                        || equipmentVo.getDeviceStatus() == 6;
            }).collect(Collectors.toList());

            List<EquipmentVo> breakdown = datas.stream().filter(equipmentVo -> {
                return equipmentVo.getDeviceStatus() == 4;
            }).collect(Collectors.toList());
            result.setBreakdownSum(breakdown.size());
            result.setNormalSum(normal.size());
            result.setOfflineSum(offline.size());
            result.setWarningSum(warning.size());
            Set<String> equipmentTypes = EquipmentTypeConst.equipmentTypes.keySet();
            List<RunningResponse> runningResponses = new ArrayList<>();
            for (String equipmentType : equipmentTypes) {
                RunningResponse runningResponse = RunningResponse.builder().build();
                runningResponse.setEquipmentType(equipmentType);
                runningResponse.setBreakdownSum(breakdown.stream().filter(equipmentVo -> {
                    return equipmentType.equals(equipmentVo.getEquipmentType());
                }).count());
                runningResponse.setNormalSum(normal.stream().filter(equipmentVo -> {
                    return equipmentType.equals(equipmentVo.getEquipmentType());
                }).count());
                runningResponse.setOfflineSum(offline.stream().filter(equipmentVo -> {
                    return equipmentType.equals(equipmentVo.getEquipmentType());
                }).count());
                runningResponse.setWarningSum(warning.stream().filter(equipmentVo -> {
                    return equipmentType.equals(equipmentVo.getEquipmentType());
                }).count());
                runningResponses.add(runningResponse);
            }
            List<RunningResponse> runningResponsesCopy = new ArrayList<>();
            RunningResponse detector = RunningResponse.builder().equipmentType("detector").breakdownSum(0L)
                    .normalSum(0L).offlineSum(0L).warningSum(0L).build();
            runningResponsesCopy.add(detector);

            runningResponses.forEach(runningResponse -> {
                if (EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode()
                        .equals(runningResponse.getEquipmentType()) ||
                        EquipmentType.INDEPENDENT_GAS_DETECTOR.getCode()
                                .equals(runningResponse.getEquipmentType())) {
                    detector.setBreakdownSum(runningResponse.getBreakdownSum() + detector.getBreakdownSum());
                    detector.setNormalSum(runningResponse.getNormalSum() + detector.getNormalSum());
                    detector.setOfflineSum(runningResponse.getOfflineSum() + detector.getOfflineSum());
                    detector.setWarningSum(runningResponse.getWarningSum() + detector.getWarningSum());
                } else {
                    runningResponsesCopy.add(runningResponse);
                }
            });
            result.setRunnings(runningResponsesCopy);
            result.setCount(result.getBreakdownSum() + result.getNormalSum() + result.getOfflineSum() + result.getWarningSum());
            if (result.getBreakdownSum() == 0 || result.getCount() == 0) {
                result.setBreakdownProportion(0.0 + "%");
            } else {
                result.setBreakdownProportion(new BigDecimal(result.getBreakdownSum())
                        .divide(new BigDecimal(result.getCount()), 2, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal(100)) + "%");
            }
            if (result.getWarningSum() == 0 || result.getCount() == 0) {
                result.setWarningProportion(0.0 + "%");
            } else {
                result.setWarningProportion(new BigDecimal(result.getWarningSum())
                        .divide(new BigDecimal(result.getCount()), 2, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal(100)) + "%");
            }
            if (result.getOfflineSum() == 0 || result.getCount() == 0) {
                result.setOfflineProportion(0.0 + "%");

            } else {
                result.setOfflineProportion(new BigDecimal(result.getOfflineSum())
                        .divide(new BigDecimal(result.getCount()), 2, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal(100)) + "%");
            }
            if (result.getNormalSum() == 0 || result.getCount() == 0) {
                result.setNormalProportion(0.0 + "%");
            } else {
                result.setNormalProportion(new BigDecimal(result.getNormalSum())
                        .divide(new BigDecimal(result.getCount()), 2, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal(100)) + "%");
            }

        } else {

            String[] str = new String[]{"Gas_alarm_controller", "detector", "home_gas_detector"};
            List<RunningResponse> runningResponsesCopy = new ArrayList<>();
            for (String s : str) {
                runningResponsesCopy.add(RunningResponse.builder().equipmentType(s).breakdownSum(0L)
                        .normalSum(0L).offlineSum(0L).warningSum(0L).build());

            }

            result.setNormalProportion("0.0%");
            result.setOfflineProportion("0.0%");
            result.setBreakdownProportion("0.0%");
            result.setWarningProportion("0.0%");
            result.setRunnings(runningResponsesCopy);
        }

        log.info("equipmentRunningInfo-result:{}", JSONObject.toJSONString(result));
        return result;
    }


    /**
     * 工单情况
     *
     * @param startTime
     * @param endTime
     * @param type
     * @return
     */
    @Override
    public List<OrderConditionResponse> orderCondition(String startTime, String endTime, int type) {
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        //int templateType = fieldTemplateService.getBySpId().getTemplateType();
        //TODO 工单模板
        //模版1mbp
        //模版2时刻助手
        String format = DateUtil.format(new Date(), "yyyy-MM-dd");
        String startDate = startTime;
        String endDate = endTime;
        List<OrderConditionResponse> responses = new ArrayList<>();
        List<OrderConditionResponse> responsesCopy = new ArrayList<>();
        //List<WorkOrderHistory> workOrderHistories = new ArrayList<>();
        List<WorkOrderHistory> completeList = new ArrayList<>();

        //工单系统为MBP
        //List<WorkOrderHistory> workOrderHistoriesUpdate = new ArrayList<>();
        QueryWrapper<WorkOrderHistory> queryWrapper = new QueryWrapper<>();
        QueryWrapper<WorkOrderHistory> queryWrapperUpdate = new QueryWrapper<>();
        LambdaQueryWrapper<WorkOrderHistory> or = queryWrapper.lambda().or();
        LambdaQueryWrapper<WorkOrderHistory> orUpdate = queryWrapperUpdate.lambda().or();
        or.in(WorkOrderHistory::getSpId, spIds).eq(WorkOrderHistory::getIsDeleted, 0);
        orUpdate.in(WorkOrderHistory::getSpId, spIds).eq(WorkOrderHistory::getIsDeleted, 0);
        if (type == 0) {
            or.like(WorkOrderHistory::getCreatedAt, format);
            orUpdate.like(WorkOrderHistory::getUpdatedAt, format);
        } else {
            //计算日期
            if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
                endDate = DateUtil.format(DateUtil.offsetDay(new Date(), -1), "yyyy-MM-dd");
                startDate = DateUtil.format(DateUtil.offsetDay(new Date(), -7), "yyyy-MM-dd");
            }

            or.between(WorkOrderHistory::getCreatedAt, startDate, DateUtil.format(DateUtil.offsetDay(new Date(), 0), "yyyy-MM-dd"));
            orUpdate.between(WorkOrderHistory::getUpdatedAt, startDate, DateUtil.format(DateUtil.offsetDay(new Date(), 0), "yyyy-MM-dd"));
        }
        List<WorkOrderHistory> workOrderHistoriesUpdate = workOrderHistoryMapper.selectList(orUpdate);
        log.info("orderCondition-or:{}", JSONObject.toJSONString(or));
        List<WorkOrderHistory> workOrderHistories = workOrderHistoryMapper.selectList(or);
        if (!CollectionUtil.isEmpty(workOrderHistoriesUpdate)) {
            List<Long> ids = new ArrayList<>();
            workOrderHistories.forEach(workOrderHistory -> {
                ids.add(workOrderHistory.getId());
            });
            for (WorkOrderHistory workOrderHistory : workOrderHistoriesUpdate) {
                if (!ids.contains(workOrderHistory.getId())) {
                    workOrderHistories.add(workOrderHistory);
                }
            }

        }
        log.info("orderCondition-workOrderHistories:{}，workOrderHistoriesUpdate:{}", JSONObject.toJSONString(workOrderHistories),
                JSONObject.toJSONString(workOrderHistoriesUpdate));

        if (CollectionUtil.isEmpty(workOrderHistories) && type == 0) {
            OrderConditionResponse orderConditionResponse = new OrderConditionResponse();
            orderConditionResponse.setDate(DateUtil.format(new Date(), "yyyy-MM-dd"));
            List<OrderConditionSonsResponse> objects = new ArrayList<>();
            for (int j = 1; j < 4; j++) {
                OrderConditionSonsResponse sons = new OrderConditionSonsResponse();
                sons.setType(j);
                sons.setAppealNum(0);
                sons.setCompleteNum(0);
                objects.add(sons);
            }
            orderConditionResponse.setList(objects);
            responsesCopy.add(orderConditionResponse);
            return responsesCopy;
        }

        workOrderHistories.forEach(workOrderHistory -> {
            workOrderHistory.setCreateDate(DateUtil.format(workOrderHistory.getCreatedAt(), "yyyy-MM-dd"));
            workOrderHistory.setUpdateDate(DateUtil.format(workOrderHistory.getUpdatedAt(), "yyyy-MM-dd"));
        });
        workOrderHistories.forEach(workOrderHistory -> {
            if (workOrderHistory.getHandleStatus() == 1) completeList.add(workOrderHistory);
        });

        Map<String, List<WorkOrderHistory>> collect = workOrderHistories.stream()
                .collect(Collectors.groupingBy(WorkOrderHistory::getCreateDate, Collectors.toList()));
        if (!CollectionUtil.isEmpty(workOrderHistories) && collect.size() > 0  ) {
            collect.forEach((s, aLong) -> {
                int num = 0;
                for (WorkOrderHistory workOrderHistory : aLong) {
                    if (!workOrderHistory.getCreateDate()
                            .equals(workOrderHistory.getUpdateDate()))
                        num = num + 1;
                }
                List<OrderConditionSonsResponse> orderConditionSonsResponses = new ArrayList<>();
                OrderConditionResponse conditionResponse = new OrderConditionResponse();
                for (int i = 1; i < 4; i++) {
                    OrderConditionSonsResponse orderConditionSonsResponse = new OrderConditionSonsResponse();
                    int finalI = i;
                    long appealNum = aLong.stream().filter(workOrderHistory -> {
                        return workOrderHistory.getOrderType() == finalI;
                    }).count();
                    long completeNum = 0L;
                    orderConditionSonsResponse.setType(i);
                    orderConditionSonsResponse.setAppealNum(appealNum);
                    if (!CollectionUtil.isEmpty(completeList)) {
                        for (WorkOrderHistory workOrderHistory : completeList) {
                            if (workOrderHistory.getUpdateDate().equals(s) && workOrderHistory.getOrderType() == finalI)
                                completeNum = completeNum + 1;
                        }
                    }
                    orderConditionSonsResponse.setCompleteNum(completeNum);
                    orderConditionSonsResponses.add(orderConditionSonsResponse);

                }
                conditionResponse.setDate(s);
                conditionResponse.setList(orderConditionSonsResponses);
                responses.add(conditionResponse);
            });
        }
        log.info("orderCondition--responses:{}",JSONObject.toJSONString(responses));
        if (type >= 1) {
            List<String> days = DateFormatUtil.getDays(startDate, endDate, "yyyy-MM-dd", 1, new ArrayList<>());
            if (!CollectionUtil.isEmpty(days)) {
                for (String day : days) {
                    int i = 0;
                    for (OrderConditionResponse respons : responses) {
                        if (day.equals(respons.getDate())) {
                            responsesCopy.add(respons);
                            i = 1;
                            continue;
                        }
                    }
                    if (i == 0) {
                        OrderConditionResponse orderConditionResponse = new OrderConditionResponse();
                        orderConditionResponse.setDate(day);
                        List<OrderConditionSonsResponse> objects = new ArrayList<>();
                        for (int j = 1; j < 4; j++) {
                            OrderConditionSonsResponse sons = new OrderConditionSonsResponse();
                            sons.setType(j);
                            sons.setAppealNum(0);
                            Long completeNum = 0L;
                            if (!CollectionUtil.isEmpty(completeList)) {
                                for (WorkOrderHistory workOrderHistory : completeList) {
                                    if (workOrderHistory.getUpdateDate().equals(day)
                                            && workOrderHistory.getOrderType() == j)
                                        completeNum = completeNum + 1;
                                }
                            }
                            sons.setCompleteNum(completeNum);
                            objects.add(sons);
                        }
                        orderConditionResponse.setList(objects);
                        responsesCopy.add(orderConditionResponse);
                    }

                }
            }
        } else {
            log.info("orderCondition--responses:{}",JSONObject.toJSONString(responses));
            for (OrderConditionResponse respons : responses) {
                respons.getList().forEach(orderConditionSonsResponse -> {
                    long completeNum=0;
                    if (!CollectionUtil.isEmpty(completeList)
                            &&orderConditionSonsResponse.getCompleteNum()==0) {
                        for (WorkOrderHistory workOrderHistory : completeList) {
                            if (workOrderHistory.getUpdateDate().equals(format)
                                    && workOrderHistory.getOrderType() == orderConditionSonsResponse.getType())
                                completeNum = completeNum + 1;
                        }
                    }
                    orderConditionSonsResponse.setCompleteNum(completeNum+orderConditionSonsResponse.getCompleteNum());

                });

            }
            responsesCopy = responses;
        }
        log.info("orderCondition-responses:{}", JSONObject.toJSONString(responses));
        return responsesCopy;
    }

    /**
     * 管理中心数据
     *
     * @return
     */
    @Override
    public PrimaryDataResponse primaryData() {
        String spId = ApplicationUtils.getWorkingSpId();
        //本身和下级的spId
        List<String> spIds = organizationService.getSpIds(spId);

        PrimaryDataResponse primaryDataResponse = new PrimaryDataResponse();
        List<EquipmentVo> datas = dtuMapper.selectEquipments(spIds);
        log.info("primaryData-datas:{}", JSONObject.toJSONString(datas));
        if (!CollectionUtil.isEmpty(datas)) {
            Set<String> equipmentTypes = EquipmentTypeConst.equipmentTypes.keySet();
            Map<String, Object> map = new HashMap<>();
            equipmentTypes.forEach(s -> {
                long count = datas.stream().filter(equipmentVo -> {
                    return s.equals(equipmentVo.getEquipmentType());
                }).count();
                map.put(s, count);
                log.info("primaryData-count:{},type:{}", count, s);
            });
            map.forEach((s, o) -> {
                if (s.equals(EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode()))
                    primaryDataResponse.setPointSum(Integer.parseInt(o + ""));
                if (s.equals(EquipmentType.HOME_GAS_DETECTOR.getCode()))
                    primaryDataResponse.setHomeSum(Integer.parseInt(o + ""));
                if (s.equals(EquipmentType.GAS_ALARM_CONTROLLER.getCode()))
                    primaryDataResponse.setControllerSum(Integer.parseInt(o + ""));
                if (s.equals(EquipmentType.INDEPENDENT_GAS_DETECTOR.getCode()))
                    primaryDataResponse.setIndependentSum(Integer.parseInt(o + ""));
            });
        }
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().or().eq(Consumer::getIsDeleted, 0).in(Consumer::getSpId, spIds);
        List<Consumer> consumers = consumerMapper.selectList(queryWrapper);
        log.info("primaryData-consumers:{}", JSONObject.toJSONString(consumers));
        primaryDataResponse.setUserSum(consumers.size());
        //今日报警和故障总数
        QueryWrapper<HistoryAlarm> query = new QueryWrapper<>();
        query.lambda().or().eq(HistoryAlarm::getIsDeleted, 0).in(HistoryAlarm::getSpId, spIds)
                .like(HistoryAlarm::getCreatedAt, DateUtil.format(new Date(), "yyyy-MM-dd"));
        List<HistoryAlarm> historyAlarms = historyAlarmMapper.selectList(query);
        log.info("primaryData-historyAlarms:{}", JSONObject.toJSONString(historyAlarms));
        primaryDataResponse.setWarningSum(historyAlarms.size());
        QueryWrapper<HistoryBroken> history = new QueryWrapper<>();
        history.lambda().or().eq(HistoryBroken::getIsDeleted, 0).in(HistoryBroken::getSpId, spIds)
                .like(HistoryBroken::getCreatedAt, DateUtil.format(new Date(), "yyyy-MM-dd"));
        List<HistoryBroken> historyBrokens = historyBrokenMapper.selectList(history);
        log.info("primaryData-historyBrokens:{}", JSONObject.toJSONString(historyBrokens));
        primaryDataResponse.setBreakdownSum(historyBrokens.size());
        log.info("primaryData-primaryDataResponse:{}", JSONObject.toJSONString(primaryDataResponse));
        return primaryDataResponse;
    }

    @Override
    public Map<String, Integer> getConditionSum() {
        Map<String, Integer> resultMap = new HashMap<>();
        Map<String, Integer> conditionAlarm = null;
        Map<String, Integer> conditionBroken = null;
        try {
            conditionAlarm = historyAlarmService.getConditionList(0);
            log.info("getConditionList-conditionAlarm:{}",JSONObject.toJSON(conditionAlarm));
            conditionBroken = historyBrokenService.getConditionList();
            log.info("getConditionList-conditionBroken:{}",JSONObject.toJSON(conditionBroken));
            Integer alarm = conditionAlarm.get("未处理")==null?0:conditionAlarm.get("未处理");
            Integer broken = conditionBroken.get("未处理")==null?0:conditionBroken.get("未处理");
            resultMap.put("undisposed",alarm+broken);
        } catch (Exception e) {
            log.error("getConditionSum-error:{}",e);
            resultMap.put("undisposed",0);
        }
        log.info("getConditionList-resultMap:{}",JSONObject.toJSON(resultMap));
        return resultMap;
    }

    /**
     * 数据处理，后续去除
     * @return
     */
    @Override
    public Object appealLog(String id) {
        appealLogMapper.updateSpId();
        return null;
    }

    @Override
    public AlarmDtuSumResponse alarmDtuSum() {
        AlarmDtuSumResponse alarmDtuSumResponse = new AlarmDtuSumResponse();
        String spId = ApplicationUtils.getWorkingSpId();
        //本身和下级的spId
        List<String> spIds = organizationService.getSpIds(spId);

        List<EquipmentVo> datas = dtuMapper.selectEquipments(spIds);
        log.info("primaryData-datas:{}", JSONObject.toJSONString(datas));
        if (!CollectionUtil.isEmpty(datas)) {
            alarmDtuSumResponse.setWarningSum(datas.size());
        }
        StringBuffer sb = new StringBuffer();
        for (String spid : spIds) {
            sb.append(spid).append(",");
        }
        String spid = sb.toString().substring(0, sb.toString().length() - 1);
        log.info("安全智能设备信息请求:{}", JSONUtil.toJsonStr(spid));
        ConsoleSkAlarmSecurityDeviceDataResponse securityDeviceDataResponse = consoleSkFeignClient.alarmSecurityDeviceData(spid);
        log.info("安全智能设备信息返回:{}", JSONUtil.toJsonStr(securityDeviceDataResponse));
        //烟雾设备数
        Integer smokeCnt = 0;
        //水浸设备数
        Integer waterImmersionCnt = 0;
        //SOS设备数
        Integer sosCnt = 0;
        //故障设备数
        Integer doorLockCnt = 0;
        if (securityDeviceDataResponse != null && securityDeviceDataResponse.getCode() == 0 && securityDeviceDataResponse.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(securityDeviceDataResponse.getData().getList())) {
            for (ConsoleSkSecurityDeviceDatalist deviceDatalist : securityDeviceDataResponse.getData().getList()) {
                smokeCnt = smokeCnt + deviceDatalist.getSmokeCnt();
                waterImmersionCnt = waterImmersionCnt + deviceDatalist.getWaterImmersionCnt();
                sosCnt = sosCnt + deviceDatalist.getSosCnt();
                doorLockCnt = doorLockCnt + deviceDatalist.getDoorLockCnt();
            }
        }
        alarmDtuSumResponse.setSmokeCnt(smokeCnt);
        alarmDtuSumResponse.setWaterImmersionCnt(waterImmersionCnt);
        alarmDtuSumResponse.setSosCnt(sosCnt);
        alarmDtuSumResponse.setDoorLockCnt(doorLockCnt);
        return alarmDtuSumResponse;
    }

    @Override
    public PageUtil<ScreenSmallBellItemVO> getScreenSmallBellList(ScreenSmallBellListRequest request) {
        String spId = ApplicationUtils.getWorkingSpId();
        //所属组织
        List<String> spIds = organizationService.getSpIds(spId);
        if (!org.springframework.util.StringUtils.isEmpty(request.getSpId())) {
            //如果查询条件不为空，按查询条件来
            spIds.clear();
            spIds.add(request.getSpId());
        }
        ScreenSmallBellListReqVO params = new ScreenSmallBellListReqVO();
        BeanUtils.copyProperties(request, params);
        params.setSpIds(spIds);

        List<Integer> equipmentStatus = new ArrayList<>();
        if (request.getEquipmentStatus() != null && EquipmentStatus.lowAlert == request.getEquipmentStatus()) { //报警
            equipmentStatus.add(EquipmentStatus.lowAlert);
            equipmentStatus.add(EquipmentStatus.highAlert);
            equipmentStatus.add(EquipmentStatus.alert);
        } else if (request.getEquipmentStatus() != null) { //故障，离线，正常
            equipmentStatus.add(request.getEquipmentStatus());
        }
        params.setEquipmentStatus(equipmentStatus);

        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);
        params.setFuncCodes(userFuncCodePermission.getFuncCodes());

        boolean servicePkgModeSwitch = businessNoticeService.switchValueByCode(
                BusinessNoticeParam.DIFFERENT_SERVICE_PACKAGE_MODE.getCode(),
                spId);
        String servicePkgMode = "";
        if (servicePkgModeSwitch){
            servicePkgMode = ServicePkgEnum.SMALL_BELL_ALERT.getCode();
        }
        params.setServicePkgMode(servicePkgMode);
        log.info("getScreenSmallBellList params:{}", params);
        PageUtil<ScreenSmallBellItemVO> deviceStatePage = deviceStateService.getScreenSmallBellList(params);
        return deviceStatePage;
    }
}
